package com.tvunetworks.center.user.filter;

import com.tvunetworks.center.common.exception.ServerException;
import com.tvunetworks.center.common.model.LoginUser;
import com.tvunetworks.center.common.util.JsonUtil;
import com.tvunetworks.center.common.util.Result;
import com.tvunetworks.center.common.util.ResultUtil;
import com.tvunetworks.center.user.service.UserService;
import com.tvunetworks.center.user.util.GetSessionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Etan Yang
 * @data: 2021/8/9 12:45
 * @description:
 */

@Slf4j
@WebFilter(filterName = "checkSessionFilter",urlPatterns = {"/deviceGeo/getGeoByDeviceIp/*","/deviceGeo/save/*"})
public class CheckSessionFilter implements Filter {
    @Autowired
    private UserService userService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        try {
            String checkCookie = request.getParameter("checkCookie");
            if (StringUtils.isEmpty(checkCookie)) {
                log.error("checkSessionFilter>>>>>>checkCookie is empty,param is wrongful.");
                this.sendJsonMessage(response, ResultUtil.paramErrorInfo());
                return;
            }
            if (!StringUtils.equalsIgnoreCase("True", checkCookie) && !StringUtils.equalsIgnoreCase("FALSE", checkCookie)) {
                log.error("CheckSessionFilter>>>>>>checkCookie is not true or false,param is wrongful.checkCookie:[{}]", checkCookie);
                this.sendJsonMessage(response, ResultUtil.paramErrorInfo());
                return;
            }
            if (StringUtils.equalsIgnoreCase(checkCookie, "True")) {
                String accessToken = GetSessionUtils.getToken(request);
              //  String accessToken = request.getHeader(LocalConstant.ACCESS_TOKEN_KEY);
                if (StringUtils.isEmpty(accessToken)) {
                    this.sendJsonMessage(response, ResultUtil.noLogin());
                    return;
                }
                if (StringUtils.isNotEmpty(accessToken)) {
                    Result<LoginUser> loginUser = userService.getLoginUser(accessToken);
                    //session无效,则响应出去
                    if (loginUser == null || !loginUser.assertSuccess()) {
                        this.sendJsonMessage(response, ResultUtil.noLogin());
                        return;
                    }
                }
            }
        } catch (Exception e) {
            log.error("CheckSessionFilter>>>>>>checkSessionFilter Exception,e:[{}]", e);
            throw new ServerException(ResultUtil.error("0x1", "server Exception"));
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

    private void sendJsonMessage(HttpServletResponse response, Object obj) throws Exception {
        response.setContentType("application/json; charset=utf-8");
        ServletOutputStream outputStream = response.getOutputStream();
        if (outputStream != null) {
            outputStream.print(JsonUtil.toJsonStr(obj));
            outputStream.close();
        }
    }
}
